package csc420groupproject;

import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;

public class CustomCaretListener implements CaretListener {
    /**
     *
     * @param e
     */
    public void caretUpdate(CaretEvent e) {
        //if this is the forumal area, execute this
        if(e.getSource() instanceof JTextField){
            JTextField source = (JTextField)e.getSource();
            String text = source.getText();
            int cursorLoc = e.getMark();
            if (source == ((GUI) source.getTopLevelAncestor()).formulaField) {
                GUI gui = (GUI) source.getTopLevelAncestor();
                //here we have code to highlight any helper words for the user
                String[] parsedText = gui.formulaField.getText().split("[{} \\\\\\[\\]\\^_]");
                //disable the caretListener
                gui.formulaField.removeCaretListener(this);

                int cursorLocInArray = e.getMark();
                int startHighlightLoc = 0;
                int endHighlightLoc = 0;

                for (int i = 0; i < parsedText.length; i++) {
                    if (cursorLocInArray > parsedText[i].length()) {
                        cursorLocInArray -= (parsedText[i].length() + 1);
                        startHighlightLoc += parsedText[i].length() + 1;
                    } else {
                        endHighlightLoc = startHighlightLoc + parsedText[i].length();
                        if (gui.helperWords.contains(gui.formulaField.getText()
                                .substring(startHighlightLoc, endHighlightLoc))) {
                            gui.formulaField.select(startHighlightLoc, endHighlightLoc);
                        }
                        break;
                    }
                }
                //give back the caretListener
                gui.formulaField.addCaretListener(this);


                try {
                    for (; !text.substring(cursorLoc - 1, cursorLoc).equals("\\"); cursorLoc--);
                } catch (IndexOutOfBoundsException err) {
                    //this is a special case in which nothing is in the box, or the cursor
                    //is in the first index of the text area, so we just return and
                    //do nothing else
                    return;
                }
                parsedText = text.substring(cursorLoc).split("[{} \\\\_]");
            }
        }
    }
}
